// ####ECOSHOSTGPLCOPYRIGHTBEGIN####                                        
// -------------------------------------------                              
// This file is part of the eCos host tools.                                
// Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.            
//
// This program is free software; you can redistribute it and/or modify     
// it under the terms of the GNU General Public License as published by     
// the Free Software Foundation; either version 2 or (at your option) any   
// later version.                                                           
//
// This program is distributed in the hope that it will be useful, but      
// WITHOUT ANY WARRANTY; without even the implied warranty of               
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        
// General Public License for more details.                                 
//
// You should have received a copy of the GNU General Public License        
// along with this program; if not, write to the                            
// Free Software Foundation, Inc., 51 Franklin Street,                      
// Fifth Floor, Boston, MA  02110-1301, USA.                                
// -------------------------------------------                              
// ####ECOSHOSTGPLCOPYRIGHTEND####                                          
// choosereposdlg.cpp :
//
//===========================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s):   julians
// Contact(s):  julians
// Date:        2000/10/02
// Version:     $Id: choosereposdlg.cpp,v 1.3 2002/02/28 18:30:35 julians Exp $
// Purpose:
// Description: Implementation file for ecChooseRepositoryDialog
// Requires:
// Provides:
// See also:
// Known bugs:
// Usage:
//
//####DESCRIPTIONEND####
//
//===========================================================================

// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#ifdef __GNUG__
#pragma implementation "choosereposdlg.h"
#endif

// Includes other headers for precompiled compilation
#include "ecpch.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#include "wx/cshelp.h"
#include "wx/dirdlg.h"
#include "wx/valgen.h"

#include "configtool.h"
#include "configtooldoc.h"
#include "choosereposdlg.h"

BEGIN_EVENT_TABLE(ecChooseRepositoryDialog, ecDialog)
    EVT_LISTBOX(ecID_CHOOSE_REPOSITORY_REPOS_LIST, ecChooseRepositoryDialog::OnClickListBox)
    EVT_BUTTON(ecID_CHOOSE_REPOSITORY_ADD, ecChooseRepositoryDialog::OnAdd)
    EVT_BUTTON(ecID_CHOOSE_REPOSITORY_REMOVE, ecChooseRepositoryDialog::OnRemove)
    EVT_BUTTON(wxID_OK, ecChooseRepositoryDialog::OnOK)
    EVT_BUTTON(wxID_CANCEL, ecChooseRepositoryDialog::OnCancel)
END_EVENT_TABLE()

// ----------------------------------------------------------------------------
// main frame
// ----------------------------------------------------------------------------

// Frame constructor
ecChooseRepositoryDialog::ecChooseRepositoryDialog(wxWindow* parent)
{
    SetExtraStyle(wxDIALOG_EX_CONTEXTHELP);

    ecDialog::Create(parent, ecID_CHOOSE_REPOSITORY_DIALOG, _("Choose folder for eCos repositories"),
        wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER);

    CreateControls(this);

    Centre(wxBOTH);
}

void ecChooseRepositoryDialog::CreateControls(wxWindow* parent)
{
    wxSizer *item1 = new wxBoxSizer( wxVERTICAL );

    wxStaticText *item2 = new wxStaticText( parent, wxID_STATIC, _("Please specify the eCos repositories."), wxDefaultPosition, wxDefaultSize, 0 );
    item1->Add( item2, 0, wxALIGN_CENTER_VERTICAL|wxALL, 10 );

    wxListBox *reposList = new wxListBox( parent, ecID_CHOOSE_REPOSITORY_REPOS_LIST, wxDefaultPosition, wxDefaultSize, 0, (wxString*) NULL, wxLB_HSCROLL );
    item1->Add( reposList, 1, wxGROW|wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT|wxBOTTOM, 10 );

    wxSizer *item4 = new wxBoxSizer( wxHORIZONTAL );
    item4->Add( wxDefaultCoord, wxDefaultCoord, 1, wxALIGN_CENTRE, 0 );

    wxButton *addButton = new wxButton( parent, ecID_CHOOSE_REPOSITORY_ADD, _("&Add..."), wxDefaultPosition, wxDefaultSize, 0 );
    item4->Add( addButton, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT|wxBOTTOM, 5 );

    wxButton *removeButton = new wxButton( parent, ecID_CHOOSE_REPOSITORY_REMOVE, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0 );
    item4->Add( removeButton, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT|wxBOTTOM, 5 );
    removeButton->Enable(FALSE);

    wxButton *okButton = new wxButton( parent, wxID_OK, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 );
    item4->Add( okButton, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT|wxBOTTOM, 5 );

    wxButton *cancelButton = new wxButton( parent, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
    item4->Add( cancelButton, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT|wxBOTTOM, 5 );

    item1->Add( item4, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT|wxBOTTOM, 5 );

#ifdef __WXGTK__
    wxButton *contextButton = new wxContextHelpButton( parent );
    item4->Add( contextButton, 0, wxALIGN_CENTRE|wxALL, 5 );
#endif

    parent->SetAutoLayout( TRUE );
    parent->SetSizer( item1 );
    parent->Layout();
    item1->Fit( parent );
    item1->SetSizeHints( parent );

    parent->FindWindow( ecID_CHOOSE_REPOSITORY_ADD)->SetFocus();

    // Add context-sensitive help text
    parent->FindWindow( ecID_CHOOSE_REPOSITORY_ADD )->SetHelpText(_("Browse for the folder, then add to repositories."));
    parent->FindWindow( ecID_CHOOSE_REPOSITORY_REMOVE )->SetHelpText(_("Remove selected repository."));
    parent->FindWindow( wxID_OK )->SetHelpText(_("Closes the dialog and loads the selected repository."));
    parent->FindWindow( wxID_CANCEL )->SetHelpText(_("Closes the dialog without loading a repository."));

    // Parser repositorys
    m_strRepositorys = wxGetApp().GetConfigToolDoc()->m_strRepository;

    if(!m_strRepositorys.IsEmpty())
    {
        while(TRUE)
        {
#ifdef __CYGWIN__
            size_t index = m_strRepositorys.Index(wxT(";"));
#else
            size_t index = m_strRepositorys.Index(wxT(":"));
#endif
            if(index != wxNOT_FOUND)
            {
                reposList->Append(m_strRepositorys.SubString(0, index - 1));
                m_strRepositorys.erase(0, index + 1);
            }
            else
            {
                reposList->Append(m_strRepositorys);
                break;
            }
        }
    }

#if __WXGTK__
    parent->FindWindow( wxID_CONTEXT_HELP )->SetHelpText(_("Invokes context-sensitive help for the clicked-on window."));
#endif
}

void ecChooseRepositoryDialog::OnClickListBox(wxCommandEvent& event)
{
    wxListBox* reposList = (wxListBox*) FindWindow( ecID_CHOOSE_REPOSITORY_REPOS_LIST );
    wxArrayInt selections;

    reposList->GetSelections(selections);
    FindWindow( ecID_CHOOSE_REPOSITORY_REMOVE )->Enable( selections.GetCount() > 0 );
}

void ecChooseRepositoryDialog::OnAdd(wxCommandEvent& event)
{
    wxListBox* reposList = (wxListBox*) FindWindow( ecID_CHOOSE_REPOSITORY_REPOS_LIST );
    wxArrayInt selections;
    wxDirDialog dialog(this, wxT("Repository path"));

    if (wxID_OK == dialog.ShowModal())
    {
        wxString path = dialog.GetPath();
        path = path.Strip(wxString::both);

        if(!path.IsEmpty())
        {
            if(ecFileName(ecFileName(path) + wxT("ecos.db")).Exists()
            || ecFileName(ecFileName(path) + ecFileName(wxT("ecc")) + wxT("ecos.db")).Exists()
            || ecFileName(ecFileName(path) + ecFileName(wxT("packages")) + wxT("ecos.db")).Exists())
            {
                // Do not contain 'packages' sub folder
                if(ecFileName(ecFileName(path) + wxT("ecos.db")).Exists())
                {
                    path = wxPathOnly(path);
                }

                // Check whether same as exist one
                for (int i = 0; i < reposList->GetCount(); i++)
                {
                    wxString existPath = reposList->GetString(i);
                    if(existPath == path)
                    {
                        wxString msg = wxString::Format(_("Repository %s already exists."), path.c_str());
                        wxMessageBox(msg);
                        return;
                    }
                }

                // Now append to the repository list
                reposList->Append(path);
            }
            else
            {
                wxString msg = wxString::Format(_("%s does not like a valid eCos repository."), path.c_str());
                wxMessageBox(msg);
                return;
            }
        }
    }

    reposList->GetSelections(selections);
    FindWindow( ecID_CHOOSE_REPOSITORY_REMOVE )->Enable( selections.GetCount() > 0 );
}

void ecChooseRepositoryDialog::OnRemove(wxCommandEvent& event)
{
    wxListBox* reposList = (wxListBox*) FindWindow( ecID_CHOOSE_REPOSITORY_REPOS_LIST );
    wxArrayInt selections;

    reposList->GetSelections(selections);
    int nListSelCount = selections.GetCount ();
    if (nListSelCount > 0)
    {
        for (int i = 0; i < selections.GetCount(); i++)
        {
            reposList->Delete(selections[i]);
        }
    }

    reposList->GetSelections(selections);
    FindWindow( ecID_CHOOSE_REPOSITORY_REMOVE )->Enable( selections.GetCount() > 0 );
}

void ecChooseRepositoryDialog::OnCancel(wxCommandEvent& event)
{
    event.Skip();
}

void ecChooseRepositoryDialog::OnOK(wxCommandEvent& event)
{
    m_strRepositorys = wxT("");

    wxListBox* reposList = (wxListBox*) FindWindow( ecID_CHOOSE_REPOSITORY_REPOS_LIST );
    for (int i = 0; i < reposList->GetCount(); i++)
    {
        wxString path = reposList->GetString(i);

        m_strRepositorys += path;
#ifdef __CYGWIN__
        m_strRepositorys += wxT(";");
#else
        m_strRepositorys += wxT(":");
#endif
    }

    if(m_strRepositorys.IsEmpty())
    {
        wxMessageBox(_("Choose one eCos repository at least."));
        return; // Don't Skip so we don't dismiss the dialog
    }

    // Skip last ";" or ":"
    m_strRepositorys = m_strRepositorys.Left(m_strRepositorys.Length() - 1);

    event.Skip();
}

wxString ecChooseRepositoryDialog::GetFolder()
{
    return m_strRepositorys;
}
